/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bean;

import dao.ProviderDao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import pojo.Provider;

/**
 *
 * @author javauser
 */
public class AddProviderBean extends org.apache.struts.action.ActionForm
{ 
    private Pattern pattern;
    private Matcher matcher;
    private Pattern pattern1;
    private Matcher matcher1;
    private Pattern pattern2;
    private Matcher matcher2;
    private static final String IPADDRESS_PATTERN ="^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
    private static final String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
    private static final String scpath="((\\w+)*\\[a-zA-Z0_9]+)?";
    private String providerName="";
    private String type="";
    private String tableName="";
    private String scriptPath="";
    private String host="";
    private String remoteDir="";
    private  String fileName="";
    private String fileExtension="";
    private String userName="";
    private String password="";
    private String localDir="";
    private String downloadDate;
    private String[] columnnames;
    private String[]  columntypes;
    private Integer[] accuracylevels;
    private boolean[] required;
    private String schedule="";
    private String modifier="";
    private String startDate="";
    private Date starteDated;
    private String startTime="";
    private String[] day;
    private String parameter="";
    private String accuracyLevel="";
    private String index="";
    private String[] month;
    
    public Date getStarteDated() 
    {
        Date date=null;
        try 
        {
            String str_date=getStartDate();
            DateFormat formatter=new SimpleDateFormat("MM/dd/yyyy");
            java.util.Date d=(java.util.Date)formatter.parse(str_date);
            date=new Date(d.getTime());
        }
        catch (ParseException ex) 
        {
            ex.printStackTrace();
        }
        return date;
    }

    public String[] getMonth() {
        return month;
    }

    public void setMonth(String[] month) {
        this.month = month;
    }

    public void setStarteDated(Date starteDated) {
        this.starteDated = starteDated;
    }
    
    public String getIndex() {
        return index;
    }

    public void setIndex(String index) {
        this.index = index;
    }
    /**
     * @return
     */
    public String getAccuracyLevel() {
        return accuracyLevel;
    }

    public void setAccuracyLevel(String accuracyLevel) {
        this.accuracyLevel = accuracyLevel;
    }

    public String getParameter() 
    {
        return parameter;
    }

    public void setParameter(String parameter) 
    {
        this.parameter = parameter;
    }
    
    public boolean[] getRequired() {
        return required;
    }

    public void setRequired(boolean[] required) {
        this.required = required;
    }
    public Integer[] getAccuracylevels() {
        return accuracylevels;
    }

    public void setAccuracylevels(Integer[] accuracylevels) {
        this.accuracylevels = accuracylevels;
    }
    public Date getStartDated() 
    {
        Date date=null;
        try 
        {  
            String str_date=getStartDate();
            
            DateFormat formatter ; 
            formatter = new SimpleDateFormat("MM/dd/yyyy");
            java.util.Date d = (java.util.Date)formatter.parse(str_date);
            date = new Date(d.getTime());
            System.out.println("sql dateeee"+date.toString());
            System.out.println("sql dateeee haha"+date);
        } 
        catch (Exception e)
        {
            System.out.println("Exception :"+e);  
        }  
        return date;
    }
   
    public String[] getColumnnames() 
    {
        return columnnames;
    }

    public void setColumnnames(String[] columnnames) {
        this.columnnames = columnnames;
    }

    public String[] getColumntypes() {
        return columntypes;
    }

    public void setColumntypes(String[] columntypes) {
        this.columntypes = columntypes;
    }

    public String[] getDay() {
        return day;
    }

    public void setDay(String[] day) {
        this.day = day;
    }

    public String getModifier() {
        return modifier;
    }

    public void setModifier(String modifier) {
        this.modifier = modifier;
    }

    public String getSchedule() {
        return schedule;
    }

    public void setSchedule(String schedule) {
        this.schedule = schedule;
    }

    public String getStartDate() {
        return startDate;
    }

    public void setStartDate(String startDate) {
        this.startDate = startDate;
    }

    public String getStartTime() {
        return startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }
    

    public String getDownloadDate() {
        return downloadDate;
    }

    public void setDownloadDate(String downloadDate) {
        this.downloadDate = downloadDate;
    }

    public String getFileExtension() {
        return fileExtension;
    }

    public void setFileExtension(String fileExtension) {
        this.fileExtension = fileExtension;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public String getLocalDir() {
        return localDir;
    }

    public void setLocalDir(String localDir) {
        this.localDir = localDir;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRemoteDir() {
        return remoteDir;
    }

    public void setRemoteDir(String remoteDir) {
        this.remoteDir = remoteDir;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
    /**
     *
     */
    public AddProviderBean() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public String getProviderName() {
        return providerName;
    }

    public void setProviderName(String providerName) {
        this.providerName = providerName;
    }

    public String getScriptPath() {
        return scriptPath;
    }

    public void setScriptPath(String scriptPath) {
        this.scriptPath = scriptPath;
    }

    public String getTableName() {
        return getProviderName()+"_dim";
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) 
    {
        this.type = type;
    }
    
    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param request The HTTP Request we are processing.
     * @return
     */
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if(getIndex().equalsIgnoreCase("newprovider"))
        {
             pattern2 = Pattern.compile(scpath);
             boolean result2=validateSCPath(getScriptPath());
             if (getProviderName() == null || getProviderName().length() < 1) 
             {
                errors.add("EmptyProviderName", new ActionMessage("error.providername"));
             }
             if(getProviderName() != null){
                 try {
                    String url ="jdbc:mysql://localhost:3306/dimensionproject";
                    DriverManager.registerDriver(new com.mysql.jdbc.Driver() );
                    Connection c=DriverManager.getConnection(url, "root", "root");
                    ProviderDao pdao=new ProviderDao(c);
                    Provider pro=pdao.getByName(getProviderName());
                    if(pro != null ){
                        errors.add("InvalidName", new ActionMessage("error.invalidname"));
                    }
                    } 
                catch (SQLException ex) {
                    ex.printStackTrace();
                    }
             }
            if(getType().equals("0"))
            {
                errors.add("EmptyProviderType", new ActionMessage("error.providertype"));
            }
            if(getScriptPath().length()<1 || getScriptPath()==null)
            {
                errors.add("EmptyScriptPath", new ActionMessage("error.scriptpath"));
            }
            else
            {
                if(!getScriptPath().endsWith(".sql") && !getScriptPath().endsWith(".SQL")){
                    errors.add("InvalidScriptFile", new ActionMessage("error.invalidscriptfile"));
                }
            }
        }
        
        if(getIndex().equalsIgnoreCase("ftpinfo"))
        {
            pattern = Pattern.compile(IPADDRESS_PATTERN);
            pattern1=Pattern.compile(regex);
            boolean result=validateIP(getHost());
            boolean result1=validateURL(getHost());
            if(getHost()==null || getHost().length()<1)
            {
                errors.add("EmptyHost", new ActionMessage("error.host"));
            }
            else
            {
                if(result==false)
                {
                    if(result1== false)
                    {
                        errors.add("EmptyHost", new ActionMessage("error.host"));
                    }
                }
            }
            if(getRemoteDir()==null || getRemoteDir().length()<1)
            {
                errors.add("EmptyRemoteDir", new ActionMessage("error.path"));
            }
            else
            {
                if(!getRemoteDir().contains("C:\\")&!getRemoteDir().contains("c:\\"))
                {
                    if(!getRemoteDir().contains("D:\\")&!getRemoteDir().contains("d:\\"))
                    {
                        if(!getRemoteDir().contains("E:\\")&!getRemoteDir().contains("e:\\"))
                        {
                            if(!getRemoteDir().contains("F:\\")&!getRemoteDir().contains("f:\\"))
                            {
                                if(!getRemoteDir().contains("G:\\")&!getRemoteDir().contains("g:\\"))
                                {
                                    if(!getRemoteDir().contains("H:\\")&!getRemoteDir().contains("h:\\"))
                                    {
                                        if(getRemoteDir().charAt(0) !='/')
                                        {
                                            errors.add("EmptyRemoteDir", new ActionMessage("error.path"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if(getFileName()== null || getFileName().length()<1)
            {
                errors.add("EmptyFileName", new ActionMessage("error.filename")); 
            }
            if(getFileExtension()==null ||getFileExtension().length()<1){
                errors.add("EmptyFileExtension", new ActionMessage("error.fileextension"));
            }
            if(getFileExtension().equalsIgnoreCase("exe"))
            {
                errors.add("EmptyFileExtension", new ActionMessage("error.fileextension")); 
            }
            if(getUserName()==null ||getUserName().length()<1)
            {
                errors.add("EmptyUserName", new ActionMessage("error.username"));
            }
            if(getLocalDir()== null || getLocalDir().length()<1)
            {
                errors.add("EmptyLocalDir", new ActionMessage("error.path"));
            }
            else
            {
                if(!getLocalDir().contains("C:\\")&!getLocalDir().contains("c:\\"))
                {
                    if(!getLocalDir().contains("D:\\")&!getLocalDir().contains("d:\\"))
                    {
                        if(!getLocalDir().contains("E:\\")&!getLocalDir().contains("e:\\"))
                        {
                            if(!getLocalDir().contains("F:\\")&!getLocalDir().contains("f:\\"))
                            {
                                if(!getLocalDir().contains("G:\\")&!getLocalDir().contains("g:\\"))
                                {
                                    if(!getLocalDir().contains("H:\\")&!getLocalDir().contains("h:\\"))
                                    {
                                        if(getLocalDir().charAt(0) !='/')
                                        {
                                            errors.add("EmptyLocalDir", new ActionMessage("error.path"));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }        
        if(getIndex().equalsIgnoreCase("scheduledata"))
        {
            try 
            {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
                String dateNow = formatter.format(cal.getTime());
                java.util.Date dn=formatter.parse(dateNow);
                System.out.println("MyDateccccccccccccccccccccccccc"+dn);
                java.util.Date du=new java.util.Date(getStartDated().getTime());
                
                if(getSchedule().equals("0"))
                {
                    errors.add("EmptySchedule", new ActionMessage("error.schedule"));
                }
//                if(getModifier()==null || getModifier().length()<1)
//                {
//                    errors.add("EmptyModifier", new ActionMessage("error.modifier"));
//                }
                System.out.println("Date Now is Equallllllllllllllllllll"+new java.util.Date().getTime());
                System.out.println("User Date is Equallllllllllllllllllll"+getStartDated().getTime());
                if(getStartDated()==null)
                {
                    errors.add("EmptyStartDate", new ActionMessage("error.startdate"));
                }
                else
                {
                    if( !du.equals(dn))
                    {
                        if(du.before(dn))
                        {
                           errors.add("EmptyStartDate", new ActionMessage("error.startdate")); 
                        }
                    }
                }
                if(getStartTime()==null || getStartTime().length()<1)
                {
                    errors.add("EmptyStartTime", new ActionMessage("error.starttime"));
                }
//                if(getDay().length == 0){
//                    errors.add("EmptyDay", new ActionMessage("error.dayerror"));
//                }
            } catch (ParseException ex) {
                Logger.getLogger(AddProviderBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return errors;
    }
    public boolean validateIP(final String ip){		  
	  matcher = pattern.matcher(ip);
	  return matcher.matches();	    	    
    }
    public boolean validateURL(final String url){		  
	  matcher1 = pattern1.matcher(url);
	  return matcher1.matches();	    	    
    }
    public boolean validateSCPath(final String scpath1){		  
	  matcher2 = pattern2.matcher(scpath1);
	  return matcher2.matches();	    	    
    }
    
}
